package com.sskj.motherboard.server;

import com.sskj.motherboard.vo.FrameMessage;
import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ClientManager {

    private static final Map<String, Channel> CLIENTS = new ConcurrentHashMap<>();

    /**
     * 注册客户端
     *
     * @param clientId 客户端Id
     * @param channel  客户端通道
     */
    public static void register(String clientId, Channel channel) {
        if (clientId == null || clientId.trim().isEmpty()) {
            return;
        }

        CLIENTS.putIfAbsent(clientId.trim(), channel);
    }

    /**
     * 获取客户端通道
     * @param clientId 客户端Id
     */
    public static void unregisterClient(String clientId) {
        if (clientId != null && !clientId.trim().isEmpty()) {
            CLIENTS.remove(clientId.trim());
        }
    }

    /**
     * 通过客户端ID获取 Channel
     * @param clientId 客户端唯一标识
     * @return 对象，如果未找到则返回 null
     */
    public static Channel getChannel(String clientId) {
        if (clientId != null && !clientId.trim().isEmpty()) {
            return CLIENTS.get(clientId.trim());
        }
        return null;
    }

    /**
     * @param clientId 客户端Id
     * @param frameMessage 消息
     * @return 是否发送成功
     */
    public static boolean sendMessageToClient(String clientId, FrameMessage frameMessage) {
        Channel channel = getChannel(clientId);
        if (channel != null && channel.isActive()) {
            frameMessage.setCommandCode((byte)0x81);
            channel.writeAndFlush(frameMessage);
        }
        return false;
    }

    /**
     * 获取当前客户端数量
     * @return 客户端数量
     */
    public static int getClientCount() {
        return CLIENTS.size();
    }
}
